import React, { Component, Suspense } from 'react';
import { connect } from 'dva';
import PageLoading from '@/components/PageLoading';
import { FormattedMessage } from 'umi-plugin-react/locale';
import { Row, Col, Button, Input, Modal, message, Drawer, Icon, Form, Pagination } from 'antd';
import styles from './index.less';

const ExtendRt = React.lazy(() => import('../extendRt'));
const Search = Input.Search;
@connect(({ question, loading }) => ({
  question,
  loading: loading.effects['question/getQuestionsByQaId'],
}))
class Qa extends Component {
  constructor(props) {
    super(props);
    this.state = {
      questions: props.addSimqa,
      question: '',
      standardQus: '',
      qaId: '',
      slots: '',
      questionIndex: null,
      isShowQusSlot: null,
      oldQus: '',
      qusList: [],
      isShard: props.isShard ? props.isShard : false,
    };
  }

  componentWillReceiveProps(nextProps, nextContext) {
    this.setState({
      qusList: nextProps.questions,
    });
  }

  addQuestion = (e, isEdit, id) => {
    e.preventDefault();
    var regu = '^[ ]+$';
    var re = new RegExp(regu);
    if (!e.target.value) {
      message.error('问题不可为空');
      return false;
    };
    if (re.test(e.target.value)) {
      message.error('问题不可为空');
      return false;
    } else {
      const val = e.target.value;
      this.setState({ question: '' }, () => {
        this.props.add(val);
      });
    }
  };

  addQusByEdit = (qaId, val) => {
    const { dispatch } = this.props;
    const that = this;
    let arr = [];
    arr = arr.concat(val);
    that.reqRef = requestAnimationFrame(() => {
      dispatch({
        type: 'question/addQus',
        payload: { id: qaId, questions: arr },
        callback: res => {
          if (!res.code) {
            message.info('添加成功');
            that.props.getQusList(qaId, true);
          }
        },
      });
    });
  };

  fixQuestion = e => {
    this.setState(
      {
        question: e.target.value,
      },
      () => {
        this.props.fixCommQuestion(this.state.question);
      }
    );
  };

  remove = (e, index, qaId) => {
    this.props.remove(e, index);
  };

  setAsk = (val, index, qaId) => {
    this.props.setStandardQus(val, index);
  };

  setAskByEdit = (qaId, e) => {
    const that = this;
    const { dispatch } = that.props;
    that.reqRef = requestAnimationFrame(() => {
      dispatch({
        type: 'question/topQus',
        payload: { id: qaId, question: e },
        callback: res => {
          if (!res.code) {
            message.info('修改成功');
            that.delSimQusByEdit(qaId, e, true);
            that.props.getTopQus(qaId);
          }
        },
      });
    });
  };

  alterQuestion = (e, k, index, qaId) => {
    this.props.modifiQus(e, k, index);
  };

  showQuestionSlot = (e, index) => {
    this.setState({
      questionIndex: index,
      oldQus: e.target.value,
    });
  };

  hideQuestionSlot = (e, index) => {
    this.setState({
      questionIndex: null,
    });
  };

  addSlotToQuestion = (val, index) => {
    const value = `${this.state.question}<${val}>`;
    this.similarInput.focus();
    this.props.modifiedSimQa(value);
    // this.setState({ question: value, });
  };

  modifiedStandard = e => {
    this.props.modifiedStandard(e.target.value);
  };

  modifiedAddSimQa = e => {
    this.props.modifiedSimQa(e.target.value);
  };

  delSimQusByEdit = (qaId, e, isSetTop) => {
    const { dispatch } = this.props;
    const that = this;
    that.reqRef = requestAnimationFrame(() => {
      dispatch({
        type: 'question/delQus',
        payload: { id: qaId, question: e },
        callback: res => {
          if (!res.code) {
            if (!isSetTop) {
              message.info('删除成功');
            };
            that.props.getQusList(qaId);
          }
        },
      });
    });
  };

  editQusByEdit = (e, qaId) => {
    const { dispatch } = this.props;
    const that = this;
    const val = e.target.value;
    if (val === that.state.oldQus) {
      return false;
    };
    that.reqRef = requestAnimationFrame(() => {
      dispatch({
        type: 'question/editQus',
        payload: { id: qaId, oldQuestion: that.state.oldQus, question: val },
        callback: res => {
          if (!res.code) {
            message.info('修改成功');
            that.props.getQaList(qaId);
          }
        },
      });
    });
  };

  addSlotToNomalQuestion = name => {
    this.standardInput.focus();
    this.props.addSlotToNomalQuestion(name);
  };

  setQusSlot = (e, val) => {
    this.setState({ isShowQusSlot: e, oldQus: val.target.value, });
  };

  hideQusSlot = () => {
    this.setState({ isShowQusSlot: null, });
  };

  addSlotToSmQuestion = (name, index) => {
    const resemblanceX = `resemblance${index}`;
    this.refs[resemblanceX].focus();
    this.props.addSlotToSmQuestion(name, index);
  };

  seeMore = () => {
    this.props.seeMore(true);
  };

  addQus = (qaId, val, isExtend) => {
    let qus = val;

    function isNull(str) {
      if (str == '') {
        return true;
      };
      var regu = '^[ ]+$';
      var re = new RegExp(regu);
      return re.test(str);
    };
    if (isNull(qus)) {
      if (isExtend) {
        qus = val;
      } else {
        return message.error('问题不能为空或仅为空格');
      }
    };
    this.setState({ question: '', }, () => {
      this.props.add(qus);
    });
  };

  getQusBySearch = e => {
    this.props.search(e);
  };

  getQusBySearch1 = val => {
    this.props.search1(val, 1);
  };

  render() {
    const formItemLayout = {
      labelCol: {
        xs: { span: 24 },
        sm: { span: 2 },
      },
      wrapperCol: {
        xs: { span: 24 },
        sm: { span: 22 },
      },
    };
    const formItemLayoutWithOutLabel = {
      wrapperCol: {
        xs: { span: 24, offset: 2 },
        sm: { span: 22, offset: 2 },
      },
    };
    const { questions, slots, standardQus, qaId, isShowMore, total, isTowDrawer, isShard, addSimqa, } = this.props;
    let arr = [];
    arr = arr.concat(questions);
    arr.unshift(standardQus);
    const { isShowQusSlot, qusList } = this.state;
    const formItems = questions.map((k, index) => (
      <Form.Item {...formItemLayoutWithOutLabel} label={''} required={false} key={index}>
        <div>
          <Input
            value={k}
            key={index}
            style={{ width: '88%' }}
            placeholder="请输入相似问题"
            ref={`resemblance${index}`}
            className={styles.inputItem}
            disabled={isShard}
            onFocus={e => this.showQuestionSlot(e, index)}
            onChange={
              qaId
                ? e => this.alterQuestion(e, k, index, qaId)
                : e => this.alterQuestion(e, k, index)
            }
          />
          <span>
            <Icon
              className="dynamic-delete-button"
              type="close-circle"
              disabled={isShard}
              onClick={qaId ? () => this.remove(k, index, qaId) : () => this.remove(k, index)}
              style={{ fontSize: 20, marginLeft: 10, cursor: 'pointer', marginTop: 5 }}
            />
            <Icon
              type="arrow-up"
              disabled={isShard}
              onClick={qaId ? () => this.setAsk(k, index, qaId) : () => this.setAsk(k, index, qaId)}
              style={{ fontSize: 20, marginLeft: 10, cursor: 'pointer', marginTop: 5 }}
            />
          </span>
        </div>
        {index === this.state.questionIndex ? (
          <div>
            {slots.map(slotItem => {
              return (
                <Button key={index} disabled={isShard} size="small" style={{ marginRight: 10 }} onClick={() => this.addSlotToSmQuestion(slotItem.name, index)}>&lt;{slotItem.name}&gt;</Button>
              );
            })}
          </div>
        ) : null}
      </Form.Item>
    ));
    return (
      <Suspense fallback={<PageLoading />}>
        {!isTowDrawer ? null : (
          <div style={{ paddingLeft: 51, marginBottom: 10 }}>
            <ExtendRt
              overall={2}
              questions={arr}
              intellectualId={qaId}
              templateData={val => this.addQus(qaId, val, true)}
            />
            <Search
              placeholder="请输入关键字"
              style={{ width: 300, marginLeft: 10 }}
              onPressEnter={e => this.getQusBySearch(e)}
              onSearch={value => {
                this.getQusBySearch1(value);
              }}
            />
          </div>
        )}
        <Form>
          <Form.Item label="标准问" {...formItemLayout}>
            <Input
              disabled={isShard}
              value={standardQus}
              style={{ width: '88%' }}
              placeholder="请添加标准问"
              className={styles.inputItem}
              ref={e => this.standardInput = e}
              onFocus={e => this.setQusSlot('qus', e)}
              onChange={e => this.modifiedStandard(e)}
            />
            <div>
              {isShowQusSlot === 'qus' ? slots.map(slotItem => {
                return (
                  <Button size="small" disabled={isShard} style={{ marginRight: 10 }} onClick={() => this.addSlotToNomalQuestion(slotItem.name)}>&lt;{slotItem.name}&gt;</Button>
                );
              }) : ''}
            </div>
          </Form.Item>
          <Form.Item label="相似问" {...formItemLayout}>
            <Row>
              <Col span={21}>
                <Input
                  value={addSimqa}
                  className={styles.inputItem}
                  onChange={e => this.modifiedAddSimQa(e)}
                  onFocus={e => this.setQusSlot('sm', e)}
                  placeholder="请输入相似问题，点击回车键继续添加"
                  ref={input => this.similarInput = input}
                  onPressEnter={e => this.addQuestion(e, false)}
                />
                <span>
                  {isShowQusSlot === 'sm' ? slots.map((slotItem, index) => {
                    return (
                      <Button key={index} disabled={isShard} size="small" style={{ display: this.state.isShowSlot, marginRight: 10 }} onClick={() => this.addSlotToQuestion(slotItem.name, index)}>&lt;{slotItem.name}&gt;</Button>
                    );
                  }) : null}
                </span>
              </Col>
              <Col span={3}>
                <Icon
                  type="plus-circle"
                  style={{ fontSize: 20, marginLeft: 10, cursor: 'pointer', marginTop: 5 }}
                  onClick={
                    qaId ? () => this.addQus(qaId, addSimqa) : () => this.addQus('', addSimqa)
                  }
                />
              </Col>
            </Row>
          </Form.Item>
          {formItems}
          <Form.Item {...formItemLayoutWithOutLabel}>
            <div style={{ textAlign: 'center' }}>
              {isShowMore ? (
                <Button style={{ margin: '0 auto' }} onClick={() => this.seeMore()}>查看全部相似问</Button>
              ) : null}
            </div>
          </Form.Item>
        </Form>
      </Suspense>
    );
  }
}

export default connect(({ user }) => ({
  currentUser: user.currentUser,
}))(Form.create()(Qa));
